﻿using System;
using System.Windows.Data;

namespace Red.Controls.Converters
{
    public sealed class StringToNullableDoubleConverter : IValueConverter
    {
        #region IValueConverter implementation

        public object Convert( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
        {
            if ( value is string )
            {
                double result;
                if ( Double.TryParse( (string)value, out result ) )
                {
                    return result;
                }
            }

            if ( targetType == typeof( double ) )
            {
                return 0.0;
            }
            return null;
        }

        public object ConvertBack( object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )
        {
            double? result = null;
            if ( value is double? )
            {
                result = (double?)value;
            }
            return result.HasValue ? result.ToString() : string.Empty;
        }
        #endregion IValueConverter implementation
    }
}
